<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    public function __construct($application)
    {
        parent::__construct($application);
        $rootDir = dirname(dirname(__FILE__));
        define('ROOT_DIR', $rootDir);
        
        Zend_Session::start();
        Zend_Registry::set('session', new Zend_Session_Namespace());

        Zend_Layout::startMvc(array('layout' => 'default', 'layoutPath' => VIEWS_PATH . '/layouts'));
        
    }

    protected function _initConfig()
    {
        $config = new Zend_Config($this->getOptions());
        Zend_Registry::set('config', $config);
        Zend_Registry::set('acl', $config->acl);
    }
    
    protected function _initDatabase()
    {
        $resource = $this->getPluginResource('db');
        $db = $resource->getDbAdapter();
        $db->query("SET NAMES 'utf8'");
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        Zend_Db_Table::setDefaultAdapter($db);
        Zend_Registry::set('db',$db);
    }

    protected function _initComponents()
    {
        require_once 'Zend/Loader.php';
        require_once 'Zend/Loader/Autoloader.php';
        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->registerNamespace('My');
        $autoloader->registerNamespace('Bvb');
        $autoloader->registerNamespace('OFC');
        $autoloader->registerNamespace('Zend');
        $autoloader->registerNamespace('Zendx');
        $autoloader->registerNamespace('ZFDebug');
        $autoloader->setFallbackAutoloader(true);
    }

    protected function _initSanitizeData()
    {
        if(isset($_SERVER['REQUEST_URI']))
            $_SERVER['REQUEST_URI'] = strip_tags($_SERVER['REQUEST_URI']);
        if(isset($_SERVER['REDIRECT_URL']))
            $_SERVER['REDIRECT_URL'] = strip_tags($_SERVER['REDIRECT_URL']);

        $filters = array('StripTags', 'StringTrim'); 
        $post = new Zend_Filter_Input($filters,null,$_POST);
        $post->setDefaultEscapeFilter('StripTags');
        Zend_Registry::set('post', $post);

        Zend_Registry::set('files', $_FILES);

        $get = new Zend_Filter_Input($filters, NULL, $_GET );
        $get->setDefaultEscapeFilter(new Zend_Filter_StringTrim());
        Zend_Registry::set('get', $get);
    }

    protected function _initCache()
    {
        $frontendOptions = array(
           'lifetime' => 7200, // cache lifetime of 2 hours
           'automatic_serialization' => true
        );

        $backendOptions = array(
            'cache_dir' => './data/cache/' // Directory where to put the cache files
        );

        // getting a Zend_Cache_Core object
        $cache = Zend_Cache::factory('Core',
                                     'File',
                                     $frontendOptions,
                                     $backendOptions);
    
        Zend_Registry::set('cache', $cache);

        Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);

    }

    protected function _initHelpers()
    {
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $viewRenderer->initView();
        $viewRenderer->view->addHelperPath('My/View/Helper/');                     // add zend view helper path
        $viewRenderer->view->addHelperPath('ZendX/JQuery/View/Helper', 'ZendX_JQuery_View_Helper');
        Zend_Controller_Action_HelperBroker::addPath('My/Controller/Action/Helper/');     // add zend action helper path

    }

    protected function _initLocale()
    {
        date_default_timezone_set('America/Sao_Paulo');

        $translator = new Zend_Translate (array (
        'adapter' => Zend_Translate::AN_ARRAY,
        'content' => '../library/translate',
        'locale' => 'pt_BR',
        'scan' => Zend_Translate::LOCALE_DIRECTORY ) );

        Zend_Validate_Abstract::setDefaultTranslator ( $translator );       
        Zend_Registry::set('Zend_Translate', $translator);
        
        $locale = new Zend_Locale('pt_BR');
        Zend_Registry::set('Zend_Locale', $locale);
        
        
    }
      
    protected function _initMenu()
    {
        $config = new Zend_Config_Ini ( APPLICATION_PATH . '/configs/navigation.ini' );
        $navigation = new Zend_Navigation ( $config );
        Zend_Registry::set('Zend_Navigation', $navigation);
    }

    public function run()
    {
        // setup front controller
        $frontController = Zend_Controller_Front::getInstance();

        $frontController->throwExceptions(true);

//        $frontController->registerPlugin(new My_Controller_Plugin_ActionSetup());
        $frontController->registerPlugin(new My_Controller_Plugin_ViewSetup(), 98);

        // acl action helper
        $aclPlugin = new My_Controller_Plugin_Acl(new My_Acl());
        $frontController->registerPlugin($aclPlugin);
    
        // run!
        try {
                $frontController->dispatch();
            } catch (Exception $exception) {
                // an exception has occurred after the ErrorController's postdispatch() has run
                if(Zend_Registry::get('config')->debug == 1) {
                    $msg = $exception->getMessage();
                    $trace = $exception->getTraceAsString();
                    echo "<div>Error: $msg<p><pre>$trace</pre></p></div>";
                } else {
                    try {
                        $logFile = Zend_Registry::get('config')->logFiles->error;
                        $log = new Zend_Log(new Zend_Log_Writer_Stream($logFile));
                        $log->debug('<html><body><pre>'.$exception->getMessage() . "\n" .  $exception->getTraceAsString() . "\n-----------------------------</pre></body></html>");
                    } catch (Exception $e) {
                        // can't log it - display error message
                        die("<p>An error occurred with logging an error!");
                    }
                }
            }

    }

}